/**
 * 重大任务; 总体计划
 *
 * 作者 nie
 * 日期 2024-10-23 14:58:05
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'layer', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        layer = layui.layer,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-task'),
        $query = $view.find('#query'),
        $status = $view.find('#status'),
    //    $taskStartDate=$view.find("#taskStartDate");
  //  $taskEndDate=$view.find("#taskEndDate");
    $searchForm = $view.find('#task-table-form');
    form.verify(validate);
    form.render();
    febs.initDictItemSelect($status, 'TASK_STATUS', null, null);
    var  ganttCustom, showType = 'day';
    var ganStartTime = formatDateDorward(getCurrentDay(),-7);
    var  ganEndTime=formatNextYear(getCurrentDay());
 //   $taskStartDate.val(ganStartTime);
 //   $taskEndDate.val(ganEndTime);
    var   ganttData = getData(ctx + "progress/list", getQueryParams())||[];
    reloadGantt();


    // laydate.render({
    //     elem: '#ID-laydate-range',
    //     type:'date',
    //     format: 'yyyy-MM-dd',
    //     btns: ['now', 'confirm'],
    //     trigger: 'click',
    //     isInitValue: true,
    //     range: ['#taskStartDate', '#taskEndDate'],
    //     done: function(value, date) {
    //         $query.click();
    //     }
    // });

    function formatNextYear(cuDate) {
        let date = new Date(cuDate)
        let y = date.getFullYear()+1
        let m = date.getMonth() + 1
        let day = date.getDate()
        m = m < 10 ? '0' + m : m
        day = day < 10 ? '0' + day : day
        return y + '-' + m + '-' + day
    }

    function   getData(url,condition){
        var result=[];
        $.ajax({
            type: "get",
            dataType: "json",
            url: url,
            data: condition,
            cache: false,
            async: false,
            success: function (data) {
                result = data || [];
            },
        });
        return result;
    }

    function renderDate(element, format,value) {
        laydate.render({
            elem: element,
            type: 'date',
            format: format,
            btns: ['now', 'confirm'],
            trigger: 'click',
            isInitValue: true,
            min:value,
        });
    }
    // 绘制 甘特图
    function reloadGantt() {
        let settings = {
            tableData: ganttData,
            showType: showType,
            startTime: ganStartTime,//右侧表格显示的最小日期
            endTime: ganEndTime,//右侧表格显示的最大日期
            leftShowColNum : 4,
            dlclick(ele) {
                // taskId,startdate, enddate
                open_dialog(ele);
            },
            //拉伸之后的回调事件
            resizeHandle(ele) {
                // taskId, startTime, endTime
                // console.log('拉伸之后的回调事件-------', ele)
                // ganttProgressMoveEnd(ele);
            },//拖拽之后的回调事件
            dragHandle(ele) {

            }
        }
        if (!ganttCustom) { // 首次渲染
            settings.elem = '#mainGanttBox';
            ganttCustom = new GanttCustom(settings);
        } else {
            ganttCustom = ganttCustom.reload(settings);
        }
    }

    $query.on('click', function () {
        ganttData = getData(ctx + "progress/list", getQueryParams())||[];
        reloadGantt();
    });

    function getQueryParams() {
     //   ganStartTime=$taskStartDate.val();
     //   ganEndTime=$taskEndDate.val();
        return {
            managers: $searchForm.find('input[name="managers"]').val()==null?"":$searchForm.find('input[name="managers"]').val().trim(),
            projectCode: $searchForm.find('input[name="projectCode"]').val()==null?"":$searchForm.find('input[name="projectCode"]').val().trim(),
            taskCode: $searchForm.find('input[name="taskCode"]').val()==null?"":$searchForm.find('input[name="taskCode"]').val().trim(),
            status: $status.val() == null ? "" : $status.val().trim(),
            planStartdate:new Date(ganStartTime),
            planEnddate: new Date(ganEndTime),
            invalidate_ie_cache: new Date()
        };
    }


    function open_dialog ({ top, left, taskId,planStartDate }) {
        $('#pqdialog').css({"left": left + "px", "top": top  + "px", "display": "flex"});
        $('#pauseTaskCode').val(taskId);
        $('#completeTaskCode').val(taskId);
        $('#pausePlanStartDate').val(planStartDate);
        $("#completePlanStartDate").val(planStartDate);
        $('#pqdialog').find('li').hover(function () {
            $(this).css("background", "antiquewhite");
        }, function () {
            $(this).css("background", "none");
        })
    }

    window.pauseTask = function(e){
        layer.open({
            type: 1,
            title: '暂停任务',
            offset: ['100px', '120px'],
            area:  ['370px', '251px'] ,
            shade:0,
            btn: ['提交'],
            closeBtn: 1,
            content: $('#pauseDialog'),
            yes: function (layero, index) {
                //   $('#pauseDialog').find('#pauseSubmit').trigger('click');
                $('#pauseSubmit').trigger('click');
            }, end() {
                debugger;
                $("#complete").css("display",'block');
            },success(){
                var  pausePlanStartDate=$('#pausePlanStartDate').val();
                renderDate('#pauseDate', 'yyyy-MM-dd',pausePlanStartDate);
                form.render();
                layui.form.render('select');
                handleResetModalPos(['#pauseTime']);
                $("#complete").css('display','none');
            }
        });
    }


    form.on('submit(pause-submit)', function (data) {
        data=data.field;
        data.taskCode=data.pauseTaskCode;
        data.planEnddate =data.pauseDate;
        data.planEndtime=data.pauseTime;
        febs.postArray(ctx + 'progress/pause' ,data,  function () {
        });
        $query.click();
    })


    window.completeTask = function(e){
        layer.open({
            type: 1,
            title: '完成任务',
            offset: ['100px','120px'],
            area:  ['370px', '172px'] ,
            btn: ['提交'],
            shade:0,
            closeBtn: 1,
            content: $('#completeDialog'),
            yes: function (layero, index) {
                $('#completeSubmit').trigger('click');
            }, end() {
                $("#pause").css("display","block");
            },success(){
                var  completePlanStartDate=$('#completePlanStartDate').val();
                renderDate('#completeDate', 'yyyy-MM-dd',completePlanStartDate);
                form.render();
                layui.form.render('select');
                handleResetModalPos(['#completeTime']);
                $("#pause").css('display','none');
            }
        });
    }

    form.on('submit(complete-submit)', function (data) {
        data=data.field;
        data.taskCode=data.completeTaskCode;
        data.planEnddate=data.completeDate;
        data.planEndtime=data.completeTime;
        febs.postArray(ctx + 'progress/complete' ,data,  function () {

        });
        $query.click();
    })

    // 点击右键菜单其他的地方隐藏菜单
    $(document).on('mousedown', function () {
        $("#pqdialog").hide();
    });

    $("#pqdialog").on("mousedown", function () {
        return false;
    }).on("contextmenu", function () {
        return false;
    });





    // ===========  时间处理
    // 获取当前日期
    function getCurrentDay() {
        var now = new Date()
        var year = now.getFullYear();//获取当前年份
        var month = now.getMonth()+1 ;//当前月份
        if (month < 10)
            month = "0" + month;
        else {
            month = month;
        }
        var day = now.getDate();//当前天份
        if (day < 10)
            day = "0" + day;
        else {
            day = day;
        }
        return year + "-" + month + "-" + day;
    }

    //当前日期往前推n天就传负数如-3，往后推就传正数如3
    function formatDateDorward(cuDate, n) {
        let date = new Date(cuDate)
        date.setDate(date.getDate() + n)
        let y = date.getFullYear()
        let m = date.getMonth() + 1
        let day = date.getDate()
        m = m < 10 ? '0' + m : m
        day = day < 10 ? '0' + day : day
        return y + '-' + m + '-' + day
    }

    function handleResetModalPos(elClass) {
        if (!Array.isArray(elClass)) {
            elClass = [elClass]
        }
        elClass.forEach(function (name) {
            $(`${name} + .layui-form-select .layui-anim-upbit`).css({
                width: '240px',
                minHeight: '200px',
                minWidth: 'unset',
                left: 'unset',
                top: 'unset',
                position: 'fixed',
            })
            $(`${name} + .layui-form-select`).click(function () {
                var clickElementOffset = $(this).offset();
                var targetTop = clickElementOffset.top + $(this).outerHeight();
                var cont = $(this).find('.layui-anim-upbit')
                // 如果出现滚动条
                $(this).parents('.layui-layer-content').scrollLeft(0);
                cont.css('top', targetTop)
            })
        })
    }

    // 图例
    var positionFlg = 0;
    $('#legend').on('click', function () {
        $('#symbolPage').toggle(function () {
            if (positionFlg == 0) {
                positionFlg = 1
            } else {
                positionFlg = 0
                $("#symbolPage").css('top', '240px')
                $("#symbolPage").css('right', 'calc(1% + 50px)')
                $("#symbolPage").css('left', '')
                $("#symbolPage").hide()
            }
        });//toggle中添加任意函数，显示隐藏的时候会有动画特效
    })

});